<script setup lang="ts">
import { computed, ref } from 'vue'
import {
  getOrderReviewStatusOptions,
  getStatusType,
  matchCode,
  StatusGroups,
} from '@/enums/rescue/OrderReviewStatus'

interface Props {
  modelValue?: string[]
  showAll?: boolean
  showCount?: boolean
  countData?: Record<string, number>
}

// 定义组件名称
defineOptions({
  name: 'OrderReviewStatusSelect',
})

const props = withDefaults(defineProps<Props>(), {
  modelValue: () => [],
  showAll: true,
  showCount: false,
  countData: () => ({}),
})

const emit = defineEmits<{
  (e: 'update:modelValue', value: string[]): void
  (e: 'change', value: string[]): void
}>()

// 状态分组
const statusGroups = [StatusGroups.PENDING_APPROVAL, StatusGroups.APPROVED]

// 展开状态管理 - 默认都折叠
const expandedGroups = ref<Record<string, boolean>>({
  [StatusGroups.PENDING_APPROVAL.code]: false,
  [StatusGroups.APPROVED.code]: false,
})

// 计算属性
const isAllSelected = computed(() => {
  return props.modelValue.length === 0
})

// 分组相关方法
function isGroupSelected(
  group: typeof StatusGroups.PENDING_APPROVAL | typeof StatusGroups.APPROVED,
): boolean {
  if (props.modelValue.length === 0) return false
  const statuses = group.statuses as readonly string[]
  return statuses.every((status) => props.modelValue.includes(status))
}

function isGroupPartialSelected(
  group: typeof StatusGroups.PENDING_APPROVAL | typeof StatusGroups.APPROVED,
): boolean {
  if (props.modelValue.length === 0) return false
  const statuses = group.statuses as readonly string[]
  const selectedInGroup = statuses.filter((status) => props.modelValue.includes(status))
  return selectedInGroup.length > 0 && selectedInGroup.length < statuses.length
}

function isStatusSelected(statusCode: string): boolean {
  return props.modelValue.includes(statusCode)
}

function getGroupType(
  group: typeof StatusGroups.PENDING_APPROVAL | typeof StatusGroups.APPROVED,
): string {
  if (group.code === 'PENDING_APPROVAL') return 'warning'
  return 'success'
}

function getGroupCount(
  group: typeof StatusGroups.PENDING_APPROVAL | typeof StatusGroups.APPROVED,
): number {
  if (!props.showCount) return (group.statuses as readonly string[]).length
  const statuses = group.statuses as readonly string[]
  return statuses.reduce((sum, status) => sum + (props.countData[status] || 0), 0)
}

function getGroupSelectedCount(
  group: typeof StatusGroups.PENDING_APPROVAL | typeof StatusGroups.APPROVED,
): number {
  if (props.modelValue.length === 0) return getGroupCount(group)
  const statuses = group.statuses as readonly string[]
  if (!props.showCount) {
    return statuses.filter((status) => props.modelValue.includes(status)).length
  }
  return statuses
    .filter((status) => props.modelValue.includes(status))
    .reduce((sum, status) => sum + (props.countData[status] || 0), 0)
}

function getTotalCount(): number {
  if (!props.showCount) return getOrderReviewStatusOptions().length
  return Object.values(props.countData).reduce((sum, count) => sum + count, 0)
}

function getStatusName(statusCode: string): string {
  const status = matchCode(statusCode)
  return status?.name || statusCode
}

// 展开/收起功能
function toggleGroupExpanded(groupCode: string) {
  expandedGroups.value[groupCode] = !expandedGroups.value[groupCode]
}

// 事件处理
function handleSelectAll() {
  const newValue: string[] = []
  emit('update:modelValue', newValue)
  emit('change', newValue)
}

function handleGroupSelect(
  group: typeof StatusGroups.PENDING_APPROVAL | typeof StatusGroups.APPROVED,
) {
  let newValue: string[] = [...props.modelValue]
  const statuses = group.statuses as readonly string[]

  if (isGroupSelected(group)) {
    // 如果全选，则取消选择该组所有状态
    newValue = newValue.filter((status) => !statuses.includes(status))
  } else {
    // 否则选择该组所有状态，先移除该组已选的，再添加全部
    newValue = newValue.filter((status) => !statuses.includes(status))
    newValue.push(...statuses)
  }

  emit('update:modelValue', newValue)
  emit('change', newValue)
}

function handleStatusSelect(statusCode: string) {
  let newValue: string[] = [...props.modelValue]

  if (newValue.includes(statusCode)) {
    // 取消选择
    newValue = newValue.filter((status) => status !== statusCode)
  } else {
    // 选择
    newValue.push(statusCode)
  }

  emit('update:modelValue', newValue)
  emit('change', newValue)
}
</script>

<template>
  <view class="status-select">
    <!-- 主要状态选择 - 水平布局 -->
    <view class="primary-status-row">
      <!-- 全部状态 -->
      <view
        v-if="showAll"
        class="status-option"
        :class="{ active: isAllSelected }"
        @tap="handleSelectAll"
      >
        <view class="status-content">
          <text class="status-title">全部状态</text>
          <text v-if="showCount" class="status-count">
            {{ getTotalCount() }}
          </text>
        </view>
      </view>

      <!-- 分组状态 -->
      <view
        v-for="group in statusGroups"
        :key="group.code"
        class="status-option"
        :class="[
          { active: isGroupSelected(group) },
          { 'partial-active': isGroupPartialSelected(group) },
          `group-${group.code.toLowerCase()}`,
        ]"
        @tap="handleGroupSelect(group)"
      >
        <view class="status-content">
          <text class="status-title">
            {{ group.name }}
          </text>
          <text v-if="showCount" class="status-count">
            {{ getGroupSelectedCount(group) }}/{{ getGroupCount(group) }}
          </text>
        </view>
      </view>
    </view>

    <!-- 详细状态选择区域 -->
    <view v-for="group in statusGroups" :key="`detail-${group.code}`" class="detail-section">
      <!-- 展开/收起按钮 -->
      <view
        v-if="isGroupSelected(group) || isGroupPartialSelected(group)"
        class="expand-toggle"
        @tap="toggleGroupExpanded(group.code)"
      >
        <text class="expand-text">{{ group.name }}详细选择</text>
        <wd-icon
          :name="expandedGroups[group.code] ? 'arrow-up' : 'arrow-down'"
          size="14px"
          color="#8E8E93"
        />
      </view>

      <!-- 子状态列表 -->
      <view
        v-show="expandedGroups[group.code]"
        class="sub-status-list"
        :class="{ expanded: expandedGroups[group.code] }"
      >
        <view
          v-for="statusCode in group.statuses as readonly string[]"
          :key="statusCode"
          class="sub-status-item"
          :class="{ active: isStatusSelected(statusCode) }"
          @tap="handleStatusSelect(statusCode)"
        >
          <view class="sub-status-content">
            <text class="sub-status-title">
              {{ getStatusName(statusCode) }}
            </text>
            <text v-if="showCount" class="sub-status-count">
              {{ props.countData[statusCode] || 0 }}
            </text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
// Apple设计系统颜色
$system-blue: #007aff;
$system-orange: #ff9500;
$system-gray: #8e8e93;
$system-gray2: #aeaeb2;
$system-gray3: #c7c7cc;
$system-gray4: #d1d1d6;
$system-gray5: #e5e5ea;
$system-gray6: #f2f2f7;

$label-primary: #000000;
$label-secondary: rgba(60, 60, 67, 0.6);
$background-primary: #ffffff;
$background-secondary: #f2f2f7;
$separator: rgba(60, 60, 67, 0.36);

.status-select {
  .primary-status-row {
    display: flex;
    gap: 12rpx;
    margin-bottom: 20rpx;

    .status-option {
      flex: 1;
      background: $background-primary;
      border-radius: 16rpx;
      border: 2px solid rgba(0, 122, 255, 0.1);
      overflow: hidden;
      transition: all 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94);
      box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.06);
      cursor: pointer;

      &:hover {
        border-color: rgba(0, 122, 255, 0.2);
        box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
      }

      &.active {
        border-color: $system-blue;
        background: rgba(0, 122, 255, 0.1);
        box-shadow: 0 4rpx 20rpx rgba(0, 122, 255, 0.2);
        position: relative;

        &::before {
          content: '';
          position: absolute;
          top: 8rpx;
          left: 8rpx;
          width: 12rpx;
          height: 12rpx;
          background: $system-blue;
          border-radius: 3rpx;
          box-shadow: 0 2rpx 4rpx rgba(0, 122, 255, 0.3);
        }
      }

      &.partial-active {
        border-color: $system-orange;
        background: rgba(255, 149, 0, 0.1);
        box-shadow: 0 4rpx 20rpx rgba(255, 149, 0, 0.2);
        position: relative;

        &::before {
          content: '';
          position: absolute;
          top: 8rpx;
          left: 8rpx;
          width: 12rpx;
          height: 12rpx;
          background: $system-orange;
          border-radius: 3rpx;
          box-shadow: 0 2rpx 4rpx rgba(255, 149, 0, 0.3);
        }
      }

      // 分组特定样式
      &.group-pending_approval {
        &.active {
          background: linear-gradient(
            135deg,
            rgba(255, 149, 0, 0.08) 0%,
            rgba(255, 204, 0, 0.05) 100%
          );
        }
      }

      &.group-approved {
        &.active {
          background: linear-gradient(
            135deg,
            rgba(52, 199, 89, 0.08) 0%,
            rgba(48, 209, 88, 0.05) 100%
          );
        }
      }

      .status-content {
        display: flex;
        flex-direction: column;
        align-items: center;
        padding: 20rpx 16rpx;
        transition: all 0.2s ease;
        text-align: center;

        .status-title {
          font-size: 26rpx;
          font-weight: 600;
          color: $label-primary;
          letter-spacing: -0.3px;
          line-height: 1.3;
          margin-bottom: 6rpx;
        }

        .status-count {
          font-size: 20rpx;
          color: $label-secondary;
          font-weight: 400;
        }
      }

      &:active .status-content {
        background: rgba(0, 0, 0, 0.03);
      }
    }
  }

  .detail-section {
    margin-bottom: 16rpx;

    .expand-toggle {
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 8rpx;
      padding: 12rpx 20rpx;
      background: rgba(0, 122, 255, 0.05);
      border: 1px solid rgba(0, 122, 255, 0.1);
      border-radius: 12rpx;
      cursor: pointer;
      transition: all 0.2s ease;
      margin-bottom: 12rpx;

      &:hover {
        background: rgba(0, 122, 255, 0.1);
      }

      &:active {
        background: rgba(0, 122, 255, 0.15);
        transform: scale(0.98);
      }

      .expand-text {
        font-size: 24rpx;
        color: $system-blue;
        font-weight: 500;
      }
    }
  }

  .sub-status-list {
    max-height: 0;
    overflow: hidden;
    transition: all 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94);
    background: rgba(0, 0, 0, 0.01);
    border-radius: 12rpx;

    &.expanded {
      max-height: 1000rpx;
    }

    .sub-status-item {
      border-bottom: 1px solid rgba(0, 0, 0, 0.05);
      transition: all 0.2s ease;
      cursor: pointer;

      &:last-child {
        border-bottom: none;
      }

      &:hover {
        background: rgba(0, 0, 0, 0.02);
      }

      &:active {
        background: rgba(0, 0, 0, 0.04);
      }

      &.active {
        background: rgba(0, 122, 255, 0.1);
        border-left: 4rpx solid $system-blue;
        position: relative;

        &::before {
          content: '';
          position: absolute;
          top: 50%;
          right: 16rpx;
          transform: translateY(-50%);
          width: 8rpx;
          height: 8rpx;
          background: $system-blue;
          border-radius: 2rpx;
          box-shadow: 0 1rpx 2rpx rgba(0, 122, 255, 0.3);
        }
      }

      .sub-status-content {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 16rpx 20rpx;

        .sub-status-title {
          flex: 1;
          font-size: 26rpx;
          font-weight: 500;
          color: $label-primary;
          letter-spacing: -0.2px;
        }

        .sub-status-count {
          padding: 4rpx 12rpx;
          background: rgba(0, 122, 255, 0.1);
          border-radius: 12rpx;
          font-size: 20rpx;
          font-weight: 600;
          color: $system-blue;
          min-width: 24rpx;
          text-align: center;
        }
      }
    }
  }
}

// 响应式设计
@media (max-width: 750rpx) {
  .status-select {
    .primary-status-row {
      gap: 8rpx;

      .status-option {
        .status-content {
          padding: 16rpx 12rpx;

          .status-title {
            font-size: 22rpx;
          }

          .status-count {
            font-size: 18rpx;
          }
        }
      }
    }

    .detail-section {
      .expand-toggle {
        padding: 10rpx 16rpx;

        .expand-text {
          font-size: 22rpx;
        }
      }

      .sub-status-list {
        .sub-status-item {
          .sub-status-content {
            padding: 14rpx 16rpx;

            .sub-status-title {
              font-size: 24rpx;
            }

            .sub-status-count {
              padding: 2rpx 10rpx;
              font-size: 18rpx;
            }
          }
        }
      }
    }
  }
}

// 暗色模式适配
@media (prefers-color-scheme: dark) {
  .status-select {
    .primary-status-row {
      .status-option {
        background: #2c2c2e;
        border-color: #48484a;

        &.active {
          background: rgba(0, 122, 255, 0.15);
          border-color: $system-blue;

          &::before {
            background: $system-blue;
            box-shadow: 0 2rpx 4rpx rgba(0, 122, 255, 0.5);
          }
        }

        &.partial-active {
          background: rgba(255, 149, 0, 0.15);
          border-color: $system-orange;

          &::before {
            background: $system-orange;
            box-shadow: 0 2rpx 4rpx rgba(255, 149, 0, 0.5);
          }
        }

        .status-content {
          .status-title {
            color: #ffffff;
          }

          .status-count {
            color: #8e8e93;
          }
        }
      }
    }

    .detail-section {
      .expand-toggle {
        background: rgba(255, 255, 255, 0.05);
        border-color: #48484a;

        .expand-text {
          color: #8e8e93;
        }
      }

      .sub-status-list {
        background: rgba(255, 255, 255, 0.02);

        .sub-status-item {
          border-bottom-color: #48484a;

          &.active {
            background: rgba(0, 122, 255, 0.15);

            &::before {
              background: $system-blue;
              box-shadow: 0 1rpx 2rpx rgba(0, 122, 255, 0.5);
            }
          }

          .sub-status-content {
            .sub-status-title {
              color: #ffffff;
            }
          }
        }
      }
    }
  }
}
</style>
